package com.xiaohai.demo.client;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 消息的消费
 * 简单模式
 */
public class MesConsumer {

    public  static String QUEUE = "helloworld";
    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();

        factory.setHost("127.0.0.1");
        factory.setPort(5672);
        factory.setUsername("guest");
        factory.setPassword("guest");
        factory.setVirtualHost("/");


        Connection connection = factory.newConnection();

        Channel channel = connection.createChannel();

        //声明队列
        channel.queueDeclare(QUEUE,true,false,false,null);

        //定义消费方法
        DefaultConsumer consumer = new DefaultConsumer(channel){
            /**
             *
             * @param consumerTag 消费者的标签
             * @param envelope 消息包的内容，可从中获取消息id，消息routingkey，交换机，消息和重传标志
             * (收到消息失败后是否需要重新发送)
             * @param properties
             * @param body
             * @throws IOException
             */
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
//
//                交换机名称
                String exchange = envelope.getExchange();
                //路由 key
                String routingKey = envelope.getRoutingKey();
                //消息ID
                long deliveryTag = envelope.getDeliveryTag();

                System.out.println("接受到的消息是"+new String(body,"utf-8"));
                super.handleDelivery(consumerTag, envelope, properties, body);
            }
        };

        /**
         * 队列名称
         * 是否自动回复，自动回复，收到消息之后向MQ发送消息，MQ删除消息设置为false  需要手动回复
         */
        channel.basicConsume(QUEUE,true,consumer);

//        channel.close();
//        connection.close();
    }
}
